package com.autonavi.collapse.task.pipe.reader.db;

import com.autonavi.collapse.task.annotation.TaskComponent;
import com.autonavi.collapse.task.context.TaskComponentContainer;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@TaskComponent(initMethod = "init")
public class DbManager {

    private Map<String, ConnectionFactory> factoryMap = new HashMap<>();

    public void init() {
        Map<String, DataSource> dataSources = TaskComponentContainer.getComponents(DataSource.class);
        String beanName;
        for (Map.Entry<String, DataSource> entry : dataSources.entrySet()) {
            beanName = entry.getKey();
            factoryMap.put(beanName, new DataSourceConnectionFactory(beanName, entry.getValue()));
        }
    }

    public void add(ConnectionFactory connectionFactory) {
        if (connectionFactory != null) {
            factoryMap.put(connectionFactory.getName(), connectionFactory);
        }
    }

    public ConnectionFactory find(String name) {
        return factoryMap.get(name);
    }
}
